package com.party.admin.web.controller.order;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.party.admin.biz.file.ExcelExportService;
import com.party.admin.biz.merchantAnalyze.MemberMerchantCountBizService;
import com.party.admin.biz.merchantAnalyze.MemberMerchantDetailBizService;
import com.party.admin.biz.order.OrderBizService;
import com.party.admin.utils.excel.ExportExcel;
import com.party.admin.web.dto.AjaxResult;
import com.party.admin.web.dto.input.common.CommonInput;
import com.party.admin.web.dto.output.order.OrderFormOutput;
import com.party.common.constant.Constant;
import com.party.common.paging.Page;
import com.party.common.utils.BigDecimalUtils;
import com.party.common.utils.DateUtils;
import com.party.common.utils.LangUtils;
import com.party.common.utils.UUIDUtils;
import com.party.core.model.BaseModel;
import com.party.core.model.activity.Activity;
import com.party.core.model.crowdfund.Project;
import com.party.core.model.crowdfund.TargetProject;
import com.party.core.model.goods.Goods;
import com.party.core.model.goods.GoodsCoupons;
import com.party.core.model.member.Member;
import com.party.core.model.member.MemberGroup;
import com.party.core.model.order.*;
import com.party.core.model.system.Dict;
import com.party.core.model.system.DictEnum;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.activity.OrderActivityBizService;
import com.party.core.service.crowdfund.IProjectService;
import com.party.core.service.crowdfund.ITargetProjectService;
import com.party.core.service.goods.IGoodsCouponsService;
import com.party.core.service.goods.IGoodsService;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.member.IMemberMerchantService;
import com.party.core.service.member.IMemberService;
import com.party.core.service.order.*;
import com.party.core.service.system.IDictService;
import com.party.core.utils.MyBeanUtils;
import com.party.pay.model.query.TradeStatus;
import com.party.pay.model.refund.WechatPayRefundResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 订单
 * 
 * @author Administrator
 *
 */
@Controller
@RequestMapping(value = "/order/order")
public class OrderFormController {

	@Autowired
	private IOrderFormService orderFormService;

	@Autowired
	private IMemberService memberService;

	@Autowired
	private IDictService dictService;

	@Autowired
	private IGoodsCouponsService goodsCouponsService;

	@Autowired
	private IOrderTradeService orderTradeService;

	@Autowired
	private IOrderRefundTradeService orderRefundTradeService;
	
	@Autowired
	private IActivityService activityService;
	
	@Autowired
	private IGoodsService goodsService;
	
	@Autowired
	private IProjectService projectService;
	
    @Autowired
    private ITargetProjectService targetProjectService;
    
    @Autowired
    private OrderBizService orderBizService;
    
    @Autowired
    private IMemberMerchantService memberMerchantService;
    @Autowired
    private OrderActivityBizService orderActivityBizService;
	@Autowired
	private ExcelExportService excelExportService;
	@Autowired
	private IOrderFormHistoryService orderFormHistoryService;
	@Autowired
	private MemberMerchantCountBizService memberMerchantCountBizService;
	@Autowired
	private MemberMerchantDetailBizService memberMerchantDetailBizService;
	@Autowired
	private IOrderFormSubInfoService orderFormSubInfoService;
	@Autowired
	private IMemberGroupService memberGroupService;

	Logger logger = LoggerFactory.getLogger(getClass());
	
	@RequestMapping(value = "goodsOrderList")
	public ModelAndView goodsOrderList(OrderForm orderForm, Page page, CommonInput commonInput) {
		ModelAndView mv = new ModelAndView("goods/orderList");
		try {
			page.setLimit(20);
			Map<String, Object> params = commonBiz(commonInput, mv);
			List<OrderForm> orderForms = orderFormService.webListPage(orderForm, params, page);
			List<OrderFormOutput> orderFormOutputs = LangUtils.transform(orderForms, input -> {
				OrderFormOutput orderFormOutput = OrderFormOutput.transform(input);
				return orderFormOutput;
			});
			Goods goods = goodsService.get(orderForm.getGoodsId());
			mv.addObject("goods", goods);
			mv.addObject("orderForm", orderForm);
			mv.addObject("orderForms", orderFormOutputs);
			mv.addObject("page", page);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mv;
	}
	
	/**
	 * 订单导出
	 * @param commonInput
	 * @param orderForm
	 * @param tradeStatus
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "exportOrder", method = RequestMethod.POST)
	public AjaxResult exportOrder(CommonInput commonInput, OrderForm orderForm, String tradeStatus, String initiatorName, HttpServletResponse response) {
		try {
			String fileName = "订单.xlsx";
			commonInput.setIsDate(1);
			Map<String, Object> params = CommonInput.appendParams(commonInput);
			params.put("isCrowdfund", "0");
			params.put("payment", 0);
			params.put("initiatorName", initiatorName);
			params.put("showProjectAuthor", true);


			// 判断输入的是否为商户号
			params.put("merchantIdBoolean", StringUtils.isNumeric(orderForm.getMerchantId()));

			// 判断输入的是否为id
			boolean initiatorBoolean = UUIDUtils.isUUID(initiatorName);
			boolean memberBoolean = UUIDUtils.isUUID(commonInput.getMemberName());
			params.put("initiatorBoolean", initiatorBoolean);
			params.put("memberBoolean", memberBoolean);
			
			Set<String> tradeStatusSet = orderBizService.searchParams(orderForm, tradeStatus, params);

			List<OrderForm> orderForms;
			if ((StringUtils.isNotEmpty(initiatorName) && !initiatorBoolean)
					|| (StringUtils.isNotEmpty(commonInput.getMemberName()) && !memberBoolean)) {
				orderForms = orderFormService.newWebListPageNew(orderForm, params);
			} else {
				orderForms = orderFormService.newWebListPage(orderForm, params);
			}

			if (tradeStatusSet.contains(TradeStatus.WX_REFUND.getCode())) {
				orderForm.setStatus(null);
			}
			List<OrderFormOutput> orderFormOutputs = LangUtils.transform(orderForms, input -> {
				OrderFormOutput orderFormOutput = OrderFormOutput.transform(input);
				// 获取商户名称
				String merchantName = orderActivityBizService.
						getMerchantName(input.getMerchantId(), input.getPaymentWay(), input.getInitiatorId(), input.getMerchantName());
				orderFormOutput.setMerchantName(merchantName);
				orderFormOutput.setPaymentWayName(PaymentWay.getValue(input.getPaymentWay()));
				orderFormOutput.setTypeName(OrderType.getValue(input.getType()));
				orderFormOutput.setStatusName(OrderStatus.getValue(input.getStatus()));
				return orderFormOutput;
			});
			ExportExcel exportExcel = new ExportExcel("", OrderFormOutput.class).setDataList(orderFormOutputs);
			String allPath = excelExportService.getExcelPath(fileName, "orderForm", exportExcel);
			return AjaxResult.success((Object) allPath);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return AjaxResult.error("导出异常");
	}

	@ResponseBody
	@RequestMapping(value = "getOrderData")
	public AjaxResult getOrderData(OrderForm orderForm, String tradeStatus, String initiatorName, CommonInput commonInput) {
		try {
			long start = System.currentTimeMillis();
			commonInput.setIsDate(1);
			Map<String, Object> params = CommonInput.appendParams(commonInput);
			params.put("payment", 0);
			params.put("initiatorName", initiatorName);

			boolean merchantIdBoolean = StringUtils.isNumeric(orderForm.getMerchantId());
			params.put("merchantIdBoolean", merchantIdBoolean);

			params.put("initiatorBoolean", UUIDUtils.isUUID(initiatorName));
			params.put("memberBoolean", UUIDUtils.isUUID(commonInput.getMemberName()));

			Set<String> tradeStatusSet = orderBizService.searchParams(orderForm, tradeStatus, params);

			/**订单总额**/
			Double orderTotal = orderBizService.getOrderTotal(orderForm, params, false, true);

			// 同行者商户总数
			Double txzOrderTotal = orderBizService.getOrderTotal(orderForm, params, true, true);

			// 退款总数
			Double refundOrderTotal = orderBizService.getOrderTotal(orderForm, params, false, false);

			// 流水总数
			Double allTotal = BigDecimalUtils.add(orderTotal, refundOrderTotal);
			allTotal = BigDecimalUtils.round(allTotal, 2);

			long end = System.currentTimeMillis();
			System.out.println("getOrderData执行完：" + (end - start) / 1000);

			if (tradeStatusSet.contains(TradeStatus.WX_REFUND.getCode())) {
				orderForm.setStatus(null);
			}

			Map<String, Object> resultMap = Maps.newHashMap();
			resultMap.put("orderTotal", orderTotal);
			resultMap.put("txzOrderTotal", txzOrderTotal);
			resultMap.put("refundOrderTotal", refundOrderTotal);
			resultMap.put("allTotal", allTotal);
			return AjaxResult.success(resultMap);
		} catch (Exception e) {
			logger.error("获取订单统计数据异常", e);
			return AjaxResult.error("获取订单统计数据异常");
		}
	}

	/**
	 * 订单列表
	 *
	 * @return
	 */
	@RequestMapping(value = "orderList")
	public ModelAndView orderList() {
		ModelAndView mv = new ModelAndView("order/orderList");
		Map<Integer, String> orderStatus = Maps.newHashMap();
		orderStatus.put(OrderStatus.ORDER_STATUS_TO_BE_PAID.getCode(), OrderStatus.ORDER_STATUS_TO_BE_PAID.getValue());
		orderStatus.put(OrderStatus.ORDER_STATUS_HAVE_PAID.getCode(), OrderStatus.ORDER_STATUS_HAVE_PAID.getValue());
		orderStatus.put(OrderStatus.ORDER_STATUS_REFUND.getCode(), OrderStatus.ORDER_STATUS_REFUND.getValue());
		orderStatus.put(OrderStatus.ORDER_STATUS_OTHER.getCode(), OrderStatus.ORDER_STATUS_OTHER.getValue());
		mv.addObject("orderStatus", orderStatus);

		Map<Integer, String> orderTypes = OrderType.convertMap();
		mv.addObject("orderTypes", orderTypes);
		return mv;
	}

	/**
	 * 订单列表
	 * @param orderForm
	 * @param tradeStatus
	 * @param page
	 * @param commonInput
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "api/list")
	public Map<String, Object> orderList1(OrderForm orderForm, String tradeStatus, String initiatorName, Page page, CommonInput commonInput) {
		commonInput.setIsDate(1);
		Map<String, Object> params = CommonInput.appendParams(commonInput);

		params.put("isCrowdfund", "0");
		params.put("payment", 0);
		params.put("initiatorName", initiatorName);

		Set<String> tradeStatusSet = orderBizService.searchParams(orderForm, tradeStatus, params);

		List<OrderForm> orderForms = orderBizService.getNewOrderList(params, initiatorName, commonInput.getMemberName(), page, orderForm);
		List<OrderFormOutput> orderFormOutputs = LangUtils.transform(orderForms, input -> {
			OrderFormOutput orderFormOutput = OrderFormOutput.transform(input);

			Integer paymentWay = input.getPaymentWay();
			orderFormOutput.setPaymentWay(paymentWay);

			String typeName = OrderType.getValue(input.getType());
			orderFormOutput.setTypeName(typeName);

			String statusName = OrderStatus.getValue(input.getStatus());
			orderFormOutput.setStatusName(statusName);

			if (null == input.getMember()) {
				orderFormOutput.setMember(new Member());
			}
			if (null == input.getInitiator()) {
				orderFormOutput.setInitiator(new Member());
			}
			return orderFormOutput;
		});

		if (tradeStatusSet.contains(TradeStatus.WX_REFUND.getCode())) {
			orderForm.setStatus(null);
		}

		Map<String, Object> ret = Maps.newHashMap();
		ret.put("data", orderFormOutputs);
		ret.put("count", page.getTotalCount());
		ret.put("code", 0);
		return ret;
	}


	/**
	 * 分销订单
	 * @param orderForm 订单信息
	 * @param page 分页参数
	 * @param distributionId 分销参数
	 * @param commonInput
	 * @return
	 */
	@RequestMapping(value = "distributorList")
	public ModelAndView distributorList(OrderForm orderForm, Page page, @RequestParam(required = false) String distributionId, CommonInput commonInput) {
		ModelAndView mv = new ModelAndView("order/distributorList");
		page.setLimit(20);
		orderForm.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
		Map<String, Object> params = commonBiz(commonInput, mv);
		params.put("distributionId", distributionId);
		List<OrderForm> orderForms = orderFormService.distributorListPage(orderForm, params, page);
		List<OrderFormOutput> orderFormOutputs = LangUtils.transform(orderForms, input -> {
			OrderFormOutput orderFormOutput = OrderFormOutput.transform(input);
			orderFormOutput.setTypeName(OrderType.getValue(input.getType()));
			Member member = memberService.get(input.getMemberId());
			orderFormOutput.setMember(member);
			return orderFormOutput;
		});
		mv.addObject("page", page);
		mv.addObject("orderForms", orderFormOutputs);

		/**订单总额**/
		Map<Integer, String> orderStatus = Maps.newHashMap();
		orderStatus.put(OrderStatus.ORDER_STATUS_TO_BE_PAID.getCode(), OrderStatus.ORDER_STATUS_TO_BE_PAID.getValue());
		orderStatus.put(OrderStatus.ORDER_STATUS_HAVE_PAID.getCode(), OrderStatus.ORDER_STATUS_HAVE_PAID.getValue());
		orderStatus.put(OrderStatus.ORDER_STATUS_REFUND.getCode(), OrderStatus.ORDER_STATUS_REFUND.getValue());
		mv.addObject("orderStatus", orderStatus);

		Dict dict = new Dict();
		dict.setType(DictEnum.ORDER_TYPE.getCode());
		dict.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
		mv.addObject("orderTypes", dictService.list(dict));
		mv.addObject("distributionId", distributionId);
		return mv;
	}


	public Map<String, Object> commonBiz(CommonInput commonInput, ModelAndView mv) {
		Map<String, Object> params = CommonInput.appendParams(commonInput);
		if (null != mv) {

			Map<Integer, String> orderStatus = Maps.newHashMap();
			orderStatus.put(OrderStatus.ORDER_STATUS_TO_BE_PAID.getCode(), OrderStatus.ORDER_STATUS_TO_BE_PAID.getValue());
			orderStatus.put(OrderStatus.ORDER_STATUS_HAVE_PAID.getCode(), OrderStatus.ORDER_STATUS_HAVE_PAID.getValue());
			orderStatus.put(OrderStatus.ORDER_STATUS_REFUND.getCode(), OrderStatus.ORDER_STATUS_REFUND.getValue());
			orderStatus.put(OrderStatus.ORDER_STATUS_OTHER.getCode(), OrderStatus.ORDER_STATUS_OTHER.getValue());

			mv.addObject("input", commonInput);
			mv.addObject("orderStatus", orderStatus);
		}
		return params;
	}

	/**
	 * 订单详情
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "orderInfo")
	public ModelAndView orderInfo(String id) {
		ModelAndView mv = new ModelAndView("order/orderInfo");
		try {
			OrderFormOutput orderFormOutput = new OrderFormOutput();
			OrderForm orderForm = orderFormService.get(id);
			if (orderForm == null) {
				OrderFormHistory orderFormHistory = orderFormHistoryService.get(id);
				MyBeanUtils.copyBeanNotNull2Bean(orderFormHistory, orderFormOutput);
			} else {
				MyBeanUtils.copyBeanNotNull2Bean(orderForm, orderFormOutput);
			}

			// 核销码
			List<GoodsCoupons> goodsCoupons = goodsCouponsService.findByOrderId(id);
			orderFormOutput.setGoodsCoupons(goodsCoupons);
			orderFormOutput.setTypeName(OrderType.getValue(orderFormOutput.getType()));
			if (orderFormOutput.getType().equals(OrderType.ORDER_ACTIVITY.getCode())
					|| OrderType.ORDER_COURSE.getCode().equals(orderFormOutput.getType())) {
				Activity activity = activityService.get(orderFormOutput.getGoodsId());
				if (activity != null) {
					orderFormOutput.setPicture(activity.getPic());
				}
			} else if (orderFormOutput.getType().equals(OrderType.ORDER_CROWD_FUND.getCode())
				|| orderFormOutput.getType().equals(OrderType.ORDER_MULTIPLE_CROWD_FUND.getCode())) {
				Project project = projectService.get(orderFormOutput.getGoodsId());
				if (project != null) {
					orderFormOutput.setPicture(project.getPic());
				}
			} else if (orderFormOutput.getType().equals(OrderType.ORDER_NOMAL.getCode())
					|| orderFormOutput.getType().equals(OrderType.ORDER_CUSTOMIZED.getCode())) {
				Goods goods = goodsService.get(orderFormOutput.getGoodsId());
				if (goods != null) {
					orderFormOutput.setPicture(goods.getPicsURL());
				}
			}

			// 获取商户名称
			String merchantName = orderActivityBizService.
					getMerchantName(orderFormOutput.getMerchantId(), orderFormOutput.getPaymentWay(),
							orderFormOutput.getInitiatorId(), orderFormOutput.getMerchantName());
			orderFormOutput.setMerchantName(merchantName);

			//交易流水
			OrderRefundTrade orderRefundTrade = orderRefundTradeService.recentlyByOrderId(id);
			WechatPayRefundResponse response = new WechatPayRefundResponse();
			if (null != orderRefundTrade && !Strings.isNullOrEmpty(orderRefundTrade.getData())) {
				response = JSONObject.toJavaObject(JSONObject.parseObject(orderRefundTrade.getData()), WechatPayRefundResponse.class);
			}

			mv.addObject("response", response);
			mv.addObject("orderForm", orderFormOutput);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mv;
	}
	
	/**
	 * 更新业务发起者编号
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "updateOrderFormInitiatorId")
	public String updateOrderFormInitiatorId(){
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("initiatorId", "1");
		List<OrderForm> orderForms = orderFormService.webListPage(new OrderForm(), params, null);
		for (OrderForm orderForm : orderForms) {
			if (StringUtils.isEmpty(orderForm.getInitiatorId())) {
				if (orderForm.getType().equals(OrderType.ORDER_ACTIVITY.getCode())) {
					Activity activity = activityService.get(orderForm.getGoodsId());
					if (activity != null) {
						orderForm.setInitiatorId(activity.getMember());
						orderFormService.update(orderForm);
					}
				} else if (orderForm.getType().equals(OrderType.ORDER_CROWD_FUND.getCode())) {
					System.err.println(orderForm.getGoodsId());
					TargetProject targetProject = targetProjectService.findByProjectId(orderForm.getGoodsId());
					if (targetProject != null && targetProject.getType().equals(Constant.CROWD_FUND_TYPE_ACTIVITY)) {
						Activity activity = activityService.get(targetProject.getTargetId());
						orderForm.setInitiatorId(activity.getMember()); // 众筹项目发起者
						orderFormService.update(orderForm);
					}
				} else if (orderForm.getType().equals(OrderType.ORDER_NOMAL.getCode()) || orderForm.getType().equals(OrderType.ORDER_CUSTOMIZED.getCode())) {
					Goods goods = goodsService.get(orderForm.getGoodsId());
					if (goods != null) {
						orderForm.setInitiatorId(goods.getMemberId());
						orderFormService.update(orderForm);
					}
				}
			}
		}
		return null;
	}


	/**
	 * 退款交易信息
	 * @param orderId 订单号
	 * @return 交互数据
	 */
	@RequestMapping(value = "refundInfo/{orderId}")
	public ModelAndView refundInfo(@PathVariable String orderId){
		ModelAndView modelAndView = new ModelAndView("order/refundInfo");
		OrderRefundTrade orderRefundTrade = orderRefundTradeService.recentlyByOrderId(orderId);
		WechatPayRefundResponse response = new WechatPayRefundResponse();
		if (null != orderRefundTrade && !Strings.isNullOrEmpty(orderRefundTrade.getData())){
			response = JSONObject.toJavaObject(JSONObject.parseObject(orderRefundTrade.getData()), WechatPayRefundResponse.class);
		}
		modelAndView.addObject("response", response);
		return modelAndView;
	}

	/**
	 * 合作商订单列表
	 * @param mmId
	 * @param page
	 * @return
	 */
	@RequestMapping("memberOrderList")
	public ModelAndView memberOrderList(String mmId, Page page, OrderForm orderForm, CommonInput commonInput) {
		ModelAndView mv = new ModelAndView("system/member/orderList");

		Map<String, Object> params = CommonInput.appendParams(commonInput);
		params.put("isCrowdfund", "0");
		params.put("payment", 0);
		page.setLimit(20);

		orderForm.setInitiatorId(mmId);
		orderForm.setStatus(OrderStatus.ORDER_STATUS_HAVE_PAID.getCode()); // 已支付

		List<OrderForm> orderForms = orderBizService.getNewOrderList(params, null,
				commonInput.getMemberName(), page, orderForm);
		List<OrderFormOutput> orderFormOutputs = LangUtils.transform(orderForms, input -> {
			OrderFormOutput orderFormOutput = OrderFormOutput.transform(input);
			String label = OrderType.getValue(input.getType());
			orderFormOutput.setTypeName(label);
			// 获取商户名称
			String merchantName = orderActivityBizService.
					getMerchantName(input.getMerchantId(), input.getPaymentWay(), input.getInitiatorId(), input.getMerchantName());
			orderFormOutput.setMerchantName(merchantName);
			return orderFormOutput;
		});
		mv.addObject("orderForms", orderFormOutputs);
		mv.addObject("page", page);
		mv.addObject("orderForm", orderForm);
		mv.addObject("input", commonInput);

		Map<String, Object> resultParams = orderBizService.memberInfoBiz(mmId);
		mv.addAllObjects(resultParams);

		// 订单总额
		Double orderTotal = orderBizService.getOrderTotal(false, mmId, orderForm.getType(), params);
		if (orderTotal != null) {
			mv.addObject("orderTotal", orderTotal);
		} else {
			mv.addObject("orderTotal", 0);
		}

		Map<Integer, String> orderTypes = Maps.newHashMap();
		orderTypes.put(OrderType.ORDER_ACTIVITY.getCode(), OrderType.ORDER_ACTIVITY.getValue());
		orderTypes.put(OrderType.ORDER_CROWD_FUND.getCode(), OrderType.ORDER_CROWD_FUND.getValue());
		mv.addObject("orderTypes", orderTypes);
		return mv;
	}

	/**
	 * 合作商订单导出
	 * @param mmId 合作商id
	 * @param orderForm 订单
	 * @param commonInput
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "exportMemberOrder", method = RequestMethod.POST)
	public AjaxResult exportMemberOrder(String mmId, OrderForm orderForm, CommonInput commonInput) {
		try {
			String fileName = "合作商订单.xlsx";
			orderForm.setInitiatorId(mmId);
			orderForm.setStatus(OrderStatus.ORDER_STATUS_HAVE_PAID.getCode()); // 已支付
			Map<String, Object> params = CommonInput.appendParams(commonInput);
			params.put("isCrowdfund", "0");
			params.put("payment", 0);

			// 判断输入的是否为id
			boolean memberBoolean = UUIDUtils.isUUID(commonInput.getMemberName());
			params.put("memberBoolean", memberBoolean);

			// 订单类型（只查活动，众筹支持订单）
			Set<Integer> orderTypes = new HashSet<Integer>();
			// orderTypes.add(OrderType.ORDER_ACTIVITY.getCode());
			// orderTypes.add(OrderType.ORDER_CROWD_FUND.getCode());
			params.put("types", orderTypes);
			List<OrderForm> orderForms;
			if (StringUtils.isNotEmpty(commonInput.getMemberName()) && !memberBoolean) {
				orderForms = orderFormService.newWebListPageNew(orderForm, params);
			} else {
				orderForms = orderFormService.newWebListPage(orderForm, params);
			}
			List<OrderFormOutput> orderFormOutputs = LangUtils.transform(orderForms, input -> {
				OrderFormOutput orderFormOutput = OrderFormOutput.transform(input);
				// 获取商户名称
				String merchantName = orderActivityBizService.
						getMerchantName(input.getMerchantId(), input.getPaymentWay(), input.getInitiatorId(), input.getMerchantName());
				orderFormOutput.setMerchantName(merchantName);
				orderFormOutput.setPaymentWayName(PaymentWay.getValue(input.getPaymentWay()));
				orderFormOutput.setTypeName(OrderType.getValue(input.getType()));
				orderFormOutput.setStatusName(OrderStatus.getValue(input.getStatus()));
				return orderFormOutput;
			});
			ExportExcel exportExcel = new ExportExcel("", OrderFormOutput.class).setDataList(orderFormOutputs);
			String allPath = excelExportService.getExcelPath(fileName, "orderForm", exportExcel);
			return AjaxResult.success((Object) allPath);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return AjaxResult.error("导出异常");
	}

	@ResponseBody
	@RequestMapping("reviseOrder")
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public AjaxResult reviseOrder() {
		try {
			MemberGroup thirdMemberManage = memberGroupService.getThirdMemberManage();
			OrderForm orderForm = new OrderForm();
			orderForm.setInitiatorId(thirdMemberManage.getId());
			List<OrderForm> orderForms = orderFormService.listPage(orderForm, null, null);
			List<String> memberIds = Lists.newArrayList();
			for (OrderForm order : orderForms) {
				if (order.getType().equals(OrderType.ORDER_CROWD_FUND.getCode())) {
					Project project = projectService.get(order.getGoodsId());
					if (project != null) {
						TargetProject targetProject = targetProjectService.findByProjectId(project.getId());
						if (targetProject != null) {
							Activity activity = activityService.get(targetProject.getTargetId());
							if (activity != null) {
								order.setInitiatorId(activity.getMember());
								orderFormService.update(order);
							}
						}
					}
				}
				memberIds.add(order.getInitiatorId());
			}
			Set<String> memberSet = new HashSet<String>(memberIds);
			for (String memberId : memberSet) {
				memberMerchantCountBizService.reviseMerchantCount(thirdMemberManage.getId(), memberId);
				memberMerchantDetailBizService.reviseMerchantDetail(thirdMemberManage.getId(), memberId);
			}
			return AjaxResult.success();
		} catch (Exception e) {
			logger.error("校正16笔订单数据异常", e);
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return AjaxResult.error(e.getMessage());
		}
	}

	@ResponseBody
	@RequestMapping(value = "exportTxzMerchantMember")
	public AjaxResult exportTxzMerchantMember() {
		try {
			SXSSFWorkbook sxssfWorkbook = orderBizService.exportTxzMerchantMember();
			if (null == sxssfWorkbook) {
				return AjaxResult.error("没有数据导出");
			}
			String fileName = "机构数据" + DateUtils.formatDate(new Date()) + ".xlsx";
			String allPath = excelExportService.getExcelPath(fileName, "orderform", new ExportExcel(), sxssfWorkbook);
			return AjaxResult.success((Object) allPath);
		} catch (Exception e) {
			logger.error("导出机构在赛事服务的金额表格异常", e);
			return AjaxResult.error("导出异常");
		}
	}

	/**
	* @Author hzq
	* @Description //初始化多场活动订单类型  之前为3  改为7
	* @Date 17:53 2019/5/6
	* @param
	* @return
	**/
	@ResponseBody
	@RequestMapping(value = "initMultipleOrderType")
	public AjaxResult initMultipleOrderType(){
		List<OrderForm> orderFormList = orderFormService.getMultipleOrder();
		for (OrderForm orderForm : orderFormList) {
			orderForm.setType(OrderType.ORDER_MULTIPLE_CROWD_FUND.getCode());
			orderFormService.update(orderForm);
		}
		return AjaxResult.success();
	}
}
